package com.iplus.ydkf.ehome.module.login;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.RequestMobileCodeCallback;
import com.avos.avoscloud.UpdatePasswordCallback;
import com.iplus.ydkf.ehome.R;
import com.iplus.ydkf.ehome.module.base.BaseActivity;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by lhtde on 2016/4/20.
 */
public class RestPasswordActivity extends BaseActivity {
    @Bind(R.id.et_restpwd_password)
    EditText et_restpwd_password;
    @Bind(R.id.et_restpwd_passwordagain)
    EditText et_restpwd_passwordagain;
    @Bind(R.id.et_restpwd_smscode)
    EditText et_restpwd_smscode;
    @Bind(R.id.btn_restpwd_phoneVerify)
    Button btn_restpwd_phoneVerify;

    private SmsReciver smsReciver = new SmsReciver();
    String ACTION_SMS_RECIVER = "android.provider.Telephony.SMS_RECEIVED";
    private String number;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            btn_restpwd_phoneVerify.setText(msg.what + "秒后重新发送");
        }
    };

    @Override
    public int bindLayout() {
        return R.layout.acitivity_resetpwd;
    }

    @Override
    public void initView(View view) {
        registSmsReciver();
        number = getIntent().getStringExtra("phoneNumber");
    }

    public void sendMessage() {
        AVUser.requestPasswordResetBySmsCodeInBackground(number, new RequestMobileCodeCallback() {
                    @Override
                    public void done(AVException e) {
                        if (isNoException(e)) {
                            btn_restpwd_phoneVerify.setEnabled(false);
                            new Thread() {
                                @Override
                                public void run() {
                                    super.run();
                                    int time = 60;
                                    while (time > 0 && time <= 60) {
                                        mHandler.sendEmptyMessage(time);
                                        time = time - 1;
                                        try {
                                            Thread.sleep(1000);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            btn_restpwd_phoneVerify.setText("重发");
                                            btn_restpwd_phoneVerify.setEnabled(true);
                                        }
                                    });
                                }
                            }.start();
                        }
                    }
                }

        );
    }

    @OnClick(R.id.btn_restpwd_phoneVerify)
    public void phoneVerify() {
        sendMessage();
    }

    @OnClick(R.id.btn_restpwd)
    public void restPassword() {
        if (isEmptyInput())
            return;
        AVUser.resetPasswordBySmsCodeInBackground(et_restpwd_smscode.getText().toString(), et_restpwd_password.getText().toString(), new UpdatePasswordCallback() {
            @Override
            public void done(AVException e) {
                if (isNoException(e)) {
                    toast("密码重置成功");
                    startActivity(new Intent(RestPasswordActivity.this, LoginActivity.class));
                }
            }
        });
    }

    @Override
    public void initData(View view) {
        sendMessage();
    }

    @Override
    public String getFragmentName() {
        return null;
    }


    private void registSmsReciver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_SMS_RECIVER);
        // 设置优先级 不然监听不到短信
        filter.setPriority(1000);
        registerReceiver(smsReciver, filter);
    }

    /**
     * 短信广播接受者 用户监听短信，自动填写验证码
     */
    private class SmsReciver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Object[] objs = (Object[]) intent.getExtras().get("pdus");
            for (Object obj : objs) {
                byte[] pdu = (byte[]) obj;
                SmsMessage sms = SmsMessage.createFromPdu(pdu);
                // 短信的内容
                String message = sms.getMessageBody();
                Log.d("log", "message     " + message);
                // 短息的手机号，如果你们公司发送验证码的号码是固定的这里可以进行一个号码的校验
                String from = sms.getOriginatingAddress();
                if (from.contains("1069073"))
                    analysisVerify(message);
                Log.d("log", "from     " + from);

            }
        }

    }

    /**
     * 解析短信并且回写  这里解析的是纯数字的短信，如果小伙伴的验证码包含字母的话，可用正则替换
     *
     * @param message
     */
    private void analysisVerify(String message) {
        try {
            int index = message.indexOf("安全码是");
            String s = (String) message.subSequence(index + 5, index + 5 + 6);
            et_restpwd_smscode.setText(s);
        } catch (Exception e) {

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消短信广播注册
        if (smsReciver != null) {
            unregisterReceiver(smsReciver);
            smsReciver = null;
        }
    }

    private boolean isEmptyInput() {
        if (TextUtils.isEmpty(et_restpwd_smscode.getText().toString())) {
            snackbar("验证码不能为空");
            return true;
        }
        if (TextUtils.isEmpty(et_restpwd_password.getText().toString()) || TextUtils.isEmpty(et_restpwd_passwordagain.getText().toString())) {
            snackbar("密码不能为空");
            return true;
        }
        if (et_restpwd_password.getText().toString().length() < 6 || et_restpwd_password.getText().toString().length() > 12) {
            snackbar("请输入6-12位长度的密码");
            return true;
        }
        if (!et_restpwd_password.getText().toString().equals(et_restpwd_passwordagain.getText().toString())) {
            snackbar("两次输入的密码不一致");
            return true;
        }
        return false;
    }
}
